/**
 * 表格组件
 *
 * @author banglong
 * @date 2016/10/21
 */
define(['text!../html/components/common/tableFixed.html!strip', 'avalon', 'tools', 'layPage'],
  function (htmlTemp, avalon, tools, laypage) {

    avalon.component('ms-tableFixed', {
      template: htmlTemp,
      defaults: {

        header: [], // 列头 中文
        row: [], // 列 英文字段
        data: [], // 数据
        colWidthArr: [], // colgroup 的 col 宽度数组

        height: 0, // table面板高度
        width: 0, // table面板宽度
        bodyHeight: 0, // table body 的高度 可能包含分页 如果包含分页 则另外计算
        operateHeight: 0, // 操作区域的 高度

        showOperation: false, // 显示操作列
        showPages: false, // 显示分页操作
        resizeLeft: 150,
        showResize: false,

        showOrder: false, // 排序
        orderIndex: -1, // 排序列
        orderStr: '', // 排序标识

        draggingIndex: -1, // 拖动的目标对象index
        oldDragLeft: 0,
        elementID: '',
        showClickClass: true,
        chooseIndex: 0,

        size: 20, // 大小
        pages: 0, // 页数
        count: 0, // 总数
        currentPages: 1, // 当前页数
        sourceData: [], // 源数组 用于分页操作
        timeObj: {},
        serverPaging: false, // 服务器分页
        serverPagingFun: function () {},

        operateWidth: 100,
        operateFixedWidth: 100,
        operateCustomEvent: {},
        operateBodyInnerCss: {
          overflow: 'scroll'
        },

        onReady: function () {
          var self = this;
          self.colWidthArr.pushArray(self.header.map(function (data, index) {
            self.width += 150;
            return 150;
          }));

          // 设置主body的高度
          if (self.showPages) {
            self.bodyHeight = self.height - 70;
          } else {
            self.bodyHeight = self.height - 30;
          }

          // 设置滚动监听
          this.initScrollListener(self);
          // 分页
          var page = document.querySelector('#' + self.elementID + 'Pages');
          self.$watch('sourceData', function () {
            if (self.showPages) {
              page.innerHTML = '';
              tools.initPage(page, self.size, self, self.data, self.sourceData.$model);

              tools.throttle(self.timeObj, function () {
                self.listenScrollBar();
              });
            } else {
              self.count = self.sourceData.length;
              self.data = self.sourceData.concat();
            }
          });
          self.$watch('data', function () {
            if (self.serverPaging) {
              page.innerHTML = '';
              laypage({
                cont: page,
                curr: self.currentPages,
                pages: self.pages,
                jump: function (obj, first) {
                  self.serverPagingFun(obj, first);
                }
              });
            }
            tools.throttle(self.timeObj, function () {
              self.listenScrollBar();
            });
          });
          // 清除排序
          $(document.body).bind('clearOrder', function () {
            if (self.showOrder) {
              self.orderStr = ''
            }
          })

          this.$watch('data', function () {
            self.listenScrollBar();
          });

          // 翻页 监听 chooseIndex 个改变
          this.$watch('chooseIndex', function (index) {
            if (this.data.length > 0) {
              this.parentHandleClickFun(index, this.data[index])
            }
          });

          this.listenScrollBar();
        },
        onClickOrderTh: function (index) {
          if (this.showOrder) {
            if (this.orderStr === 'ascending') {
              this.orderStr = 'descending'
            } else {
              this.orderStr = 'ascending'
            }
            this.orderIndex = index
            var self = this
            tools.throttle(self.timeObj, function () {
              self.handleOrder(index, self.orderStr);
            });
          }
        },
        // 排序
        orderBy: function (e, index, str) {
          e.stopPropagation();
          this.orderIndex = index;
          this.orderStr = str;
          var self = this;
          tools.throttle(self.timeObj, function () {
            self.handleOrder(index, str);
          });
        },
        // 比较方法
        compare: function compare(value1, value2) {
          if (value1 < value2) {
            return -1;
          } else if (value1 > value2) {
            return 1;
          } else {
            return 0;
          }
        },
        handleOrder: function (index, str) {
          if (this.showOrder) {
            var self = this
            var model = this.sourceData.$model;
            var loadIndex = layer.msg('正在排序中...', {
              time: 1000 //2秒关闭（如果不配置，默认是3秒）
            });
            setTimeout(function () {
              model.sort(function (a, b) {
                var key = self.row[index]
                var value1 = a[key];
                var value2 = b[key];
                // 是字符串
                if (typeof a[key] === 'string') {
                  // 是数字
                  //                if (!isNaN(parseFloat(a[key]))) {
                  //                  value1 = parseFloat(a[key].trim())
                  //                  value2 = parseFloat(b[key].trim())
                  //                }
                  // 是日期
                  if (/(?!0000)[0-9]{4}-/.test(value1)) {
                    value1 = new Date(value1)
                    value2 = new Date(value2)
                  }
                }
                if (str === 'ascending') {
                  return self.compare(value1, value2)
                } else {
                  return self.compare(value2, value1)
                }
              })
              self.sourceData.splice(0, self.sourceData.length);
              self.sourceData = model.concat();
              // 分页
              // if (this.showPages) {
              //   this.paging(this, this.serverPaging);
              // }
            })
          }
        },
        // 父类的点击方法
        parentHandleClickFun: function (index, data) {},
        handleClick: function (index) {
          this.chooseIndex = index;
          // var self = this;
          // tools.throttle(this.timeObj, function () {
          //     var data = self.data[index];
          //     self.parentHandleClickFun(index, data.$model);
          // });
        },

        // 双击选择数据
        chooseDataFun: function (data) {},
        handleDbClick: function (index) {
          var data = this.data[index];
          this.chooseDataFun(data.$model);
        },
        // 删除操作 父组件传过来的方法
        removeChooseDataFun: function () {},
        removeChooseData: function (index) {
          this.removeChooseDataFun(index);
        },
        listenScrollBar: function () {

          var targetBody = document.querySelector('#table-fixed-body-' + this.elementID);
          var targetHeader = $('#table-fixed-head-' + this.elementID);
          // 说明 有横向滚动条的出现
          if (targetBody) {
            if (targetBody.scrollWidth > targetBody.clientWidth) {
              targetHeader.css({
                width: 'auto',
                'padding-right': -this.getScrollBarWidth()
              });
              this.operateHeight = this.bodyHeight;
              this.operateFixedWidth = this.operateWidth;
            } else {
              targetHeader.css({
                'padding-right': 0
              });
              this.operateFixedWidth = this.operateWidth;
              this.operateHeight = this.bodyHeight - this.getScrollBarWidth();
              this.operateFixedWidth = this.operateWidth - this.getScrollBarWidth();
            }
            if (targetBody.scrollHeight > targetBody.clientHeight + 1) {
              targetHeader.css({
                width: 'auto',
                'padding-right': -this.getScrollBarWidth()
              });
              this.operateBodyInnerCss.overflow = 'scroll';
            } else {
              targetHeader.css({
                'padding-right': 0
              });
              // this.operateFixedWidth = this.operateWidth;
              this.operateFixedWidth = targetHeader.find('.thead th:last').width() + 12;
              this.operateHeight = this.bodyHeight - this.getScrollBarWidth();
              this.operateBodyInnerCss.overflow = 'auto';
            }
          }
        },
        // 获取滚动条宽度
        getScrollBarWidth: function () {
          return -tools.getScrollBarWidth()().vertical + 1;
        },

        initScrollListener: function (self) {
          // 滚动监听 表头固定
          var tableFixedHead = document.querySelector("#table-fixed-head-" + self.elementID + " table");
          // body内容
          var tableFixedBody = document.querySelector('#table-fixed-body-' + self.elementID);
          // 右侧操作模块
          var tableFixedRight = document.querySelector("#table-fixed-right-" + self.elementID);
          var tableFixedRightInner;
          // 是否 可以对右侧操作模块进行反向操作
          var isScroll = false;
          if (tableFixedRight) {
            tableFixedRightInner = tableFixedRight.querySelector('.table-fixed-body').querySelector('.table-body-inner');
            tableFixedRightInner.onscroll = function (e) {
              if (isScroll) {
                var target = tools.getEventTarget(e);
                tableFixedBody.scrollTop = target.scrollTop;
              }
            };
            // 进入左侧操作模块的时候 可以对左侧的表内容进行滚动
            tableFixedRightInner.onmouseenter = function () {
              isScroll = true;
            };
            tableFixedRightInner.onmouseleave = function () {
              isScroll = false;
            };
          }
          tableFixedBody.onscroll = function (e) {
            var target = tools.getEventTarget(e);
            // 表头滚动
            tableFixedHead.style.left = -target.scrollLeft + 'px';
            if (tableFixedRightInner && !isScroll) {
              // 表内容滚动
              tableFixedRightInner.scrollTop = target.scrollTop;
            }
          };
        },

        paging: function (self, serverPaging) {

        },

        // 缩放列的大小
        handleMousedown: function (event, index) {
          event = tools.getEvent(event);
          event.stopPropagation();
          this.draggingIndex = index;
          this.oldDragLeft = event.clientX;

          var self = this;
          var $body = $("body");
          $body.css("cursor", "e-resize");

          var canComputedResizeLeft = true;
          var tablePanel = document.querySelector('#table-panel-' + self.elementID);
          var target = event.target;
          for (var lx = 0; target !== null && target !== tablePanel; lx += target.offsetLeft, target = target.offsetParent);
          var oldLeftResize = lx + 10;

          $body.bind('mousemove', function (e) {

            // 计算 resize 标志 需要出现的位置
            if (canComputedResizeLeft) {
              self.resizeLeft = oldLeftResize;
              canComputedResizeLeft = false;
              self.showResize = true;
            }

            if (self.draggingIndex === index) {
              if (self.oldDragLeft < e.clientX) {
                self.resizeLeft += (e.clientX - self.oldDragLeft);
              } else {
                self.resizeLeft -= (self.oldDragLeft - e.clientX);
              }

              self.oldDragLeft = e.clientX;
              e.preventDefault();
            }
          });
          $body.bind('mouseup', function () {
            self.draggingIndex = -1;
            $body.css("cursor", "");
            $body.unbind('mouseup');
            $body.unbind('mousemove');

            // 取消显示 缩放标志
            self.showResize = false;
            // 计算 缩放宽度
            var width = self.colWidthArr[index];
            width += self.resizeLeft - oldLeftResize;
            if (width < 150) width = 150;
            self.colWidthArr.set(index, width);
            self.listenScrollBar();
          })
        }
      }
    });
  });